#pragma once

#include <iostream>
#include <signal.h>
#include "Task.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"

#define PORT 8081

class HttpServer
{
public:
  HttpServer(int port = PORT)
      : _port(port), _stop(false)
  {
  }

public:
  // 将信号 STGPIPE忽略，防止写入发生错误，OS发送信号终止服务器
  void InitServer() { signal(SIGPIPE, SIG_IGN); }
  void Loop();
  ~HttpServer(){};

private:
  int _port;
  bool _stop;
};

void HttpServer::Loop()
{
  LOG(INFO, "loop begin");
  int _listen_sock = TcpServer::GetInstance(_port)->GetSock();
  while (!_stop)
  {
    struct sockaddr_in peer;
    socklen_t peer_len = sizeof(sockaddr_in);
    int sock = accept(_listen_sock, (struct sockaddr *)&peer, &peer_len);
    if (sock < 0)
    {
      continue;
    }
    LOG(INFO, "get a link");
    // pthread_t tid;
    // int* psock_fp = new int(sock);
    // pthread_create(&tid, nullptr, Entrance::HandlerRequest, psock_fp);
    // pthread_detach(tid);
    Task task(sock);
    ThreadPool::GetInstance()->PushTask(sock);
  }
}
